<?php
class NodeAction extends AdminAction {

	#列表
	public function Index() {
		$node = M('Node')->where('level=1')->order('sort asc , id asc')->select();
		foreach ($node as $key => $value) {
			$action = M('Node')->where('pid='.$value['id'])->select();
			$node[$key]['child'] = $action;
		}
		$this->assign('node',$node);
		$this->display();

	}

	#获得子节点
	public function getChild(){
		$pid = I('get.pid');
		$map['pid'] = $pid;
		$list = M('Node')->field('id,name,title')->where($map)->select();
		$this->assign('list',$list);
		$result = $this->fetch();
		echo $result;
	}

	#添加模型
	function Add() {
		$level = I('get.level');
		$pid = I('get.pid');
		if ($level==1) {
			$nodeName = '分组';
		}elseif($level==2){
			$nodeName = '模型';
		}elseif($level==3){
			$nodeName = '方法';
		}

		$map['id'] = $pid;
		$pname = M('Node')->where($map)->getField('title');

		$this->assign('nodeName',$nodeName);		
		$this->assign('level',$level);
		$this->assign('pname',$pname);
		$this->assign('pid',$pid);
		$this->display();
	}

	#保存
	function save() {
		$obj = D('Node');
		if ($data = $obj->create()) {
			if ($obj->add($data)) {
				$map['pid'] = $data['pid'];
				$list = M('Node')->where($map)->order('sort asc , id asc')->select();
				$this->assign('list',$list);
				$url = $this->fetch('option');
				$state = 'SUCCESS';
	            $message = '添加成功';
			} else {
				$state = '添加失败';
			}
		} else {
			$state = $obj->getError();
		}
		echo $this->echo_json_str($state,$message,$url);
	}

	#编辑
	function edit() {
		$id = (int) $_GET['id'];
		if (!isset ($id)) {
			$this->error('参数错误');
		}

		$obj = M('Node');
		$list = $obj->where("id=$id")->find();
		if (!$list) {
			$this->error('信息不存在');
		} else {
			if ($list['pid']==1) {
				$nodeName = '分组';
			}elseif($list['pid']==2){
				$nodeName = '模型';
			}elseif($list['pid']==3){
				$nodeName = '方法';
			}
			$map['id']=$list['pid'];
			$pname = M('Node')->where($map)->getField('title');
			$this->assign('pname',$pname);
			$this->assign('list', $list);
			$this->display();
		}

	}

	#更新
	function update() {
		$obj = D('Node');
		if ($data = $obj->create()) {
			if ($obj->save($data)) {
				$state = 'SUCCESS';
	            $message = '编辑成功';
	            
	            $map['pid'] = $data['pid'];
				$list = M('Node')->where($map)->order('sort asc , id asc')->select();
				$this->assign('list',$list);
				$url = $this->fetch('option');
			} else {
				$state = '编辑失败';
			}
		} else {
			$state = $obj->getError();
		}
		echo $this->echo_json_str($state,$message,$url);

	}

	#删除
	function del() {

		$id = I('get.nodeID');
		if(!isset($id)){
			echo '请选择删除的节点';die;
		}

		$obj = M('Node');
		$list = $obj->where('pid='.$id)->find();
		if($list){
			echo '请先删除子节点';die;
		}

		$list = $obj->where('id='.$id)->delete();

		if($list){
			echo '1';
		}else{
			echo '删除失败';
		}
	}
	
}
?>